package com.dc.kylin.flowable.controller;

import com.dc.kylin.flowable.service.LeaveService;
import com.dc.kylin.flowable.vo.LeaveRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/api/leave")
public class LeaveController {

    @Autowired
    private LeaveService leaveService;

    // 提交请假申请
    @PostMapping("/apply")
    public ResponseEntity<?> applyLeave(@RequestBody LeaveRequest leaveRequest) {
        ProcessInstance processInstance = leaveService.startLeaveProcess(leaveRequest);
        return ResponseEntity.ok(Collections.singletonMap("processInstanceId", processInstance.getId()));
    }

    // 获取我的待办任务
    @GetMapping("/tasks")
    public ResponseEntity<?> getMyTasks(@RequestParam String userId) {
        List<Task> tasks = leaveService.getUserTasks(userId);
        return ResponseEntity.ok(tasks);
    }

    // 部门经理审批
    @PostMapping("/deptLeaderApprove")
    public ResponseEntity<?> deptLeaderApprove(
            @RequestParam String taskId,
            @RequestParam Boolean approved,
            @RequestParam(required = false) String comment) {
        leaveService.deptLeaderApprove(taskId, approved, comment);
        return ResponseEntity.ok().build();
    }

    // HR备案
    @PostMapping("/hrRecord")
    public ResponseEntity<?> hrRecord(
            @RequestParam String taskId,
            @RequestParam(required = false) String comment) {
        leaveService.hrRecord(taskId, comment);
        return ResponseEntity.ok().build();
    }

    // 获取请假申请详情
    @GetMapping("/detail")
    public ResponseEntity<?> getLeaveDetail(@RequestParam String processInstanceId) {
        LeaveRequest leaveRequest = leaveService.getLeaveRequest(processInstanceId);
        return ResponseEntity.ok(leaveRequest);
    }

    // 获取流程图
    @GetMapping("/diagram")
    public void getProcessDiagram(@RequestParam String processInstanceId, HttpServletResponse response) throws IOException {
        InputStream is = leaveService.getProcessDiagram(processInstanceId);
        response.setContentType("image/png");
        IOUtils.copy(is, response.getOutputStream());
    }
}
